<?php

namespace app\api\controller;

use addons\wechat\library\Config as ConfigService;
use app\api\model\Order;
use app\api\model\OrderGoods;
use app\api\model\ShopGoodsSpec;
use app\api\model\UserAddress;
use app\common\controller\Api;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order as WxOrder;
use think\Db;
use think\Model;
use think\Validate;

/**
 * C-购物车相关
 * @ApiWeigh    (98)
 */
class Cart extends Api {
	protected $noNeedLogin = [];
	protected $noNeedRight = ['*'];

	/**
	 * 购物车列表
	 *
	 * @ApiTitle    (购物车列表)
	 * @ApiSummary  (购物车列表)
	 * @ApiMethod   (POST)
	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
	 *
	 * @ApiReturnParams   (name="goods_list", type="object", description="商品总数")
	 * @ApiReturnParams   (name="id", type="integer", description="商品id")
	 * @ApiReturnParams   (name="cart_id", type="integer", description="购物车id")
	 * @ApiReturnParams   (name="name", type="string", description="商品名称")
	 * @ApiReturnParams   (name="goods_no", type="string", description="商品编号")
	 * @ApiReturnParams   (name="category_id", type="integer", description="商品类别id")
	 * @ApiReturnParams   (name="image", type="string", description="商品图片物理路径")
	 * @ApiReturnParams   (name="goods_price", type="string", description="商品单价")
	 * @ApiReturnParams   (name="stock_num", type="integer", description="商品库存")
	 * @ApiReturnParams   (name="total_num", type="integer", description="购买数量")
	 * @ApiReturnParams   (name="total_price", type="integer", description="合计价格")
	 *
	 * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
	 * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
	 * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
	 * @ApiReturn   ({
	"code":"状态码",
	"msg": "提示消息"
	})
	 */
	public function index() {
		$userId = $this->auth->id;
		$model  = new \app\api\model\Cart();
		$list   = $model->getList( $userId );
		$this->success( '', $list );
	}

//	/**
//	 * 自己写的废弃-购物车列表
//	 *
//	 * @ApiTitle    (购物车列表)
//	 * @ApiSummary  (购物车列表)
//	 * @ApiMethod   (POST)
//	 *
//	 * @ApiReturnParams   (name="total", type="object", description="商品总数")
//	 * @ApiReturnParams   (name="per_page", type="object", description="每页数据")
//	 * @ApiReturnParams   (name="current_page", type="object", description="当前页")
//	 * @ApiReturnParams   (name="last_page", type="object", description="最后一页")
//	 * @ApiReturnParams   (name="data", type="array", description="商品数组")
//	 * @ApiReturnParams   (name="id", type="array", description="购物车id")
//	 * @ApiReturnParams   (name="user_id", type="integer", description="用户id")
//	 * @ApiReturnParams   (name="goods_id", type="integer", description="商品id")
//	 * @ApiReturnParams   (name="num", type="integer", description="该商品添加数量")
//	 * @ApiReturnParams   (name="goods_spec_id", type="integer", description="商品规格id-忽略")
//	 * @ApiReturnParams   (name="goods_info", type="object", description="商品对象")
//	 * @ApiReturnParams   (name="goods_info.id", type="object", description="商品id")
//	 * @ApiReturnParams   (name="goods_info.image", type="object", description="商品头图物理路径")
//	 * @ApiReturnParams   (name="goods_info.name", type="object", description="商品名称")
//	 * @ApiReturnParams   (name="goods_info.goods_price", type="object", description="商品价格")
//	 * @ApiReturnParams   (name="goods_info.stock_num", type="object", description="商品库存")
//	 *
//	 * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
//	 * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
//	 * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
//	 */
//	public function index() {
//		$cartModel  = new \app\api\model\Cart();
//		$goodsModel = new \app\api\model\Goods();
//
//		$list = $cartModel
//			->where( 'user_id', $this->auth->id )
//			->order(['createtime'=>'desc'])
//			->paginate( 15 )
//			->each( function ( $item ) use ( $goodsModel ) {
//				$item['goods_info'] = $goodsModel->field('id,image,name,goods_price,stock_num')
//					->where('id',$item['goods_id'])
//					->where('status',1)
//					->find();
//			} );
//		$this->success( '', $list );
//	}

//    /**
//     * 添加购物车-有规格
//     *
//     * @ApiTitle    (添加购物车)
//     * @ApiSummary  (添加购物车)
//     * @ApiMethod   (POST)
//     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
//     * @ApiParams   (name="goods_id", type="integer", required=true, description="商品ID")
//     * @ApiParams   (name="num", type="integer", required=true, description="数量")
//     * @ApiParams   (name="goods_spec_id", type="integer", required=true, description="规格ID")
//     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
//     * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
//     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
//     * @ApiReturn   ({
//    "code":"状态码",
//    "msg": "提示消息"
//    })
//     */
//    public function add(){
//        $rules = [
//            'goods_id'=>'require',
//            'goods_spec_id'=>'require',
//            'num'=>'require|integer|gt:0',
//        ];
//        $message= [
//            'goods_id.require'=>'商品ID不能为空',
//            'goods_spec_id.require'=>'规格ID不能为空',
//            'num.require'=>'商品数量不能为空',
//        ];
//        $validate = new Validate($rules,$message);
//        $param = $this->request->param();
//        if (!$validate->check($param)) {
//            $this->error($validate->getError());
//        }
//        $userId=$this->auth->id;
//        $model=new \app\api\model\Cart();
//        $row=$model->add($userId,$param['goods_id'],$param['num'],$param['goods_spec_id']);
//        if($row){
//            $total=$model->getTotalNum($userId);
//            $this->success('添加成功',$total);
//        }else{
//            $this->error($model->getError());
//        }
//    }

	/**
	 * 添加到购物车
	 *
	 * @ApiTitle    (添加到购物车)
	 * @ApiSummary  (添加到购物车)
	 * @ApiMethod   (POST)
	 *
	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
	 *
	 * @ApiParams   (name="goods_id", type="integer", required=true, description="商品ID")
	 * @ApiParams   (name="num", type="integer", required=true, description="数量")
	 *
	 * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码:0=添加失败,1=添加成功")
	 * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
	 * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
	 */
	public function add() {
		//验证参数
		$rules    = [
			'goods_id' => 'require',
			'num'      => 'require|integer|gt:0',
		];
		$message  = [
			'goods_id.require' => '商品ID不能为空',
			'num.require'      => '商品数量不能为空',
		];
		$validate = new Validate( $rules, $message );
		$param    = $this->request->param();
		if ( !$validate->check( $param ) ) {
			$this->error( $validate->getError() );
		}
		//实例
		$userId     = $this->auth->id;
		$cartModel  = new \app\api\model\Cart();
		$goodsModel = new \app\api\model\Goods();

		//查询商品信息
		$goods_info = $goodsModel->where( 'id', $param['goods_id'] )->find();
		// 判断商品是否下架
		if ( $goods_info['status'] !== 1 ) {
			$this->error( '很抱歉，该商品已下架' );
		}
		//查询用户购物车信息
		$row = $cartModel->where( ['user_id' => $userId, 'goods_id' => $param['goods_id']] )->find();
		//判断商品库存
		$cartGoodsNum = $param['num'] + ( !empty( $row ) ? $row['num'] : 0 );
		if ( $cartGoodsNum > $goods_info['stock_num'] ) {
			$this->error( '很抱歉，商品库存不足' );
		}

		if ( $row ) {
			//若购物车已经存在该商品 则更新数量
			$row->save( ['num' => $cartGoodsNum] );
		} else {
			//反之 新增一条该商品的信息
			$cartModel->save( ['user_id' => $userId, 'goods_id' => $param['goods_id'], 'num' => $cartGoodsNum] );
		}
		$this->success( '添加购物车成功!' );
	}

//	/**
//	 * 增加购物车数量-有规格
//	 * @ApiTitle    (增加购物车数量)
//	 * @ApiSummary  (增加购物车数量)
//	 * @ApiMethod   (POST)
//	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
//	 *
//	 * @ApiParams   (name="cart_id", type="integer", required=true, description="购物车ID")
//	 * @ApiParams   (name="num", type="integer", required=false, description="数量")
//	 *
//	 * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
//	 * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
//	 * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
//	 * @ApiReturn   ({
//	"code":"状态码",
//	"msg": "提示消息"
//	})
//	 */
//	public function inc() {
//		$ids = $this->request->param( 'cart_id' );
//		$num = $this->request->param( 'num', 0, 'intval' );
//		if ( empty( $ids ) ) {
//			$this->error( '购物车ID不能为空' );
//		}
//		$info = Db::name( 'cart' )->where( ['id' => ['eq', $ids]] )->find();
//		if ( empty( $info ) ) {
//			$this->error( '商品不在购物车' );
//		}
//		$find = Db::name( 'shop_goods_spec' )->where( ['goods_spec_id' => $info['goods_spec_id']] )->find();
//		if ( empty( $find ) ) {
//			$this->error( '规格不存在' );
//		}
//		if ( $info['num'] >= $find['stock_num'] ) {
//			$this->error( '库存不足' );
//		}
//		if ( empty( $num ) ) {
//			Db::name( 'cart' )->where( ['id' => ['eq', $ids]] )->setInc( 'num' );
//		} else {
//			Db::name( 'cart' )->where( ['id' => ['eq', $ids]] )->setField( 'num', $num );
//		}
//
//		$model  = new \app\api\model\Cart();
//		$userId = $this->auth->id;
//		$total  = $model->getTotalNum( $userId );
//		$this->success( '修改成功', $total );
//	}

	/**
	 * 增加购物车数量
	 *
	 * @ApiTitle    (增加购物车数量)
	 * @ApiSummary  (增加购物车数量)
	 * @ApiMethod   (POST)
	 *
	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
	 *
	 * @ApiParams   (name="cart_id", type="integer", required=true, description="购物车ID")
	 * @ApiParams   (name="num", type="integer", required=false, description="数量:点击+号时不传值或者传0,输入具体数量时传大于0的数字")
	 *
	 * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
	 * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
	 * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
	 * @ApiReturn   ({
	"code":"状态码",
	"msg": "提示消息"
	})
	 */
	public function inc() {
		$ids = $this->request->param( 'cart_id' );
		$num = $this->request->param( 'num', 0, 'intval' );
		if ( empty( $ids ) ) {
			$this->error( '购物车ID不能为空' );
		}
		//查询购物车信息
		$info = Db::name( 'cart' )->where( ['id' => ['eq', $ids]] )->find();
		if ( empty( $info ) ) {
			$this->error( '商品不在购物车' );
		}
		$find = Db::name( 'shop_goods' )->where( ['id' => $info['goods_id']] )->find();
		if ( empty( $find ) ) {
			$this->error( '商品不存在' );
		}
		if ( $info['num'] >= $find['stock_num'] ) {
			$this->error( '库存不足' );
		}
		if ( empty( $num ) ) {
			Db::name( 'cart' )->where( ['id' => ['eq', $ids]] )->setInc( 'num' );
		} else {
			Db::name( 'cart' )->where( ['id' => ['eq', $ids]] )->setField( 'num', $num );
		}
		$this->success( '增加修改完成' );
	}

//	/**
//	 * 减少购物车数量-有规格
//	 *
//	 * @ApiTitle    (减少购物车数量)
//	 * @ApiSummary  (减少购物车数量)
//	 * @ApiMethod   (POST)
//	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
//	 * @ApiParams   (name="cart_id", type="integer", required=true, description="购物车ID")
//	 * @ApiParams   (name="num", type="integer", required=false, description="数量")
//	 * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
//	 * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
//	 * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
//	 * @ApiReturn   ({
//	"code":"状态码",
//	"msg": "提示消息"
//	})
//	 */
//	public function sub() {
//		$ids = $this->request->param( 'cart_id' );
//		$num = $this->request->param( 'num', 0, 'intval' );
//		if ( empty( $ids ) ) {
//			$this->error( '购物车ID不能为空' );
//		}
//		$info = Db::name( 'cart' )->where( ['id' => ['eq', $ids]] )->find();
//		if ( empty( $info ) ) {
//			$this->error( '商品不在购物车' );
//		}
//		if ( $info['num'] == 1 ) {
//			$this->error( '不能再减少了' );
//		}
//
//		if ( empty( $num ) ) {
//			Db::name( 'cart' )->where( ['id' => ['eq', $ids]] )->setDec( 'num' );
//		} else {
//			Db::name( 'cart' )->where( ['id' => ['eq', $ids]] )->setField( 'num', $num );
//		}
//		$model  = new \app\api\model\Cart();
//		$userId = $this->auth->id;
//		$total  = $model->getTotalNum( $userId );
//		$this->success( '修改成功', $total );
//	}

	/**
	 * 减少购物车数量
	 *
	 * @ApiTitle    (减少购物车数量)
	 * @ApiSummary  (减少购物车数量)
	 * @ApiMethod   (POST)
	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
	 *
	 * @ApiParams   (name="cart_id", type="integer", required=true, description="购物车ID")
	 * @ApiParams   (name="num", type="integer", required=false, description="数量:点击-号时不传值或者传0,输入具体数量时传大于0的数字")
	 *
	 * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
	 * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
	 * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
	 */
	public function sub() {
		$ids = $this->request->param( 'cart_id' );
		$num = $this->request->param( 'num', 0, 'intval' );
		if ( empty( $ids ) ) {
			$this->error( '购物车ID不能为空' );
		}
		$info = Db::name( 'cart' )->where( ['id' => ['eq', $ids]] )->find();
		if ( empty( $info ) ) {
			$this->error( '商品不在购物车' );
		}
		if ( $info['num'] == 1 ) {
			$this->error( '不能再减少了' );
		}

		if ( empty( $num ) ) {
			Db::name( 'cart' )->where( ['id' => ['eq', $ids]] )->setDec( 'num' );
		} else {
			Db::name( 'cart' )->where( ['id' => ['eq', $ids]] )->setField( 'num', $num );
		}
		$this->success( '减少修改成功' );
	}

//	/**
//	 * 删除购物车-有规格
//	 *
//	 * @ApiTitle    (删除购物车)
//	 * @ApiSummary  (删除购物车)
//	 * @ApiMethod   (POST)
//	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
//	 * @ApiParams   (name="cart_ids", type="string", required=true, description="购物车ID，多个英文逗号隔开")
//	 * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
//	 * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
//	 * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
//	 * @ApiReturn   ({
//	"code":"状态码",
//	"msg": "提示消息"
//	})
//	 */
//	public function del() {
//		$ids = $this->request->param( 'cart_ids' );
//		if ( empty( $ids ) ) {
//			$this->error( '请选择需要删除的商品' );
//		}
//		Db::name( 'cart' )->where( ['id' => ['in', $ids]] )->delete();
//		$this->success( '删除成功' );
//	}

	/**
	 * @ApiTitle    (删除购物车)
	 * @ApiSummary  (删除购物车)
	 * @ApiMethod   (POST)
	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
	 *
	 * @ApiParams   (name="cart_ids", type="string", required=true, description="购物车ID，多个英文逗号隔开")
	 *
	 * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
	 * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
	 * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
	 */
	public function del() {
		$ids = $this->request->param( 'cart_ids' );
		if ( empty( $ids ) ) {
			$this->error( '请选择需要删除的商品' );
		}
		Db::name( 'cart' )->where( ['id' => ['in', $ids]] )->delete();
		$this->success( '删除成功' );
	}

//	/**
//	 * @ApiTitle    (修改购物车属性)
//	 * @ApiSummary  (修改购物车属性)
//	 * @ApiMethod   (POST)
//	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
//	 * @ApiParams   (name="cart_id", type="integer", required=true, description="购物车ID")
//	 * @ApiParams   (name="goods_spec_id", type="integer", required=true, description="商品属性ID")
//	 * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
//	 * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
//	 * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
//	 * @ApiReturn   ({
//	"code":"状态码",
//	"msg": "提示消息"
//	})
//	 */
//	public function updateSpec() {
//		$rules    = [
//			'cart_id'       => 'require',
//			'goods_spec_id' => 'require',
//		];
//		$message  = [
//			'cart_id.require'       => '购物车ID不能为空',
//			'goods_spec_id.require' => '商品属性不能为空',
//		];
//		$validate = new Validate( $rules, $message );
//
//		$param = $this->request->param();
//		if ( !$validate->check( $param ) ) {
//			$this->error( $validate->getError() );
//		}
//		$model = new \app\api\model\Cart();
//		$row   = $model->where( ['id' => $param['cart_id']] )->find();
//		if ( $row ) {
//			$row->save( ['goods_spec_id' => $param['goods_spec_id']] );
//			$this->success( '修改成功' );
//		} else {
//			$this->error( '信息不存在' );
//		}
//	}

	/**
	 * 购物车结算数据
	 *
	 * @ApiTitle    (购物车结算数据)
	 * @ApiSummary  (购物车结算数据)
	 * @ApiMethod   (POST)
	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
	 *
	 * @ApiParams   (name="cart_ids", type="string", required=true, description="购物车ID,多个用英文逗号隔开即可")
	 *
	 * @ApiReturnParams   (name="goods_list[]", type="array", required=true, description="购买的商品信息[]")
	 * @ApiReturnParams   (name="id", type="array", required=true, description="商品id")
	 * @ApiReturnParams   (name="name", type="string", required=true, description="商品名称")
	 * @ApiReturnParams   (name="goods_no", type="string", required=true, description="商品编号")
	 * @ApiReturnParams   (name="category_id", type="string", required=true, description="商品类别:1=画作,2=指挥手办,3=摄影技术,4=最新作品")
	 * @ApiReturnParams   (name="image", type="string", required=true, description="商品一张缩略图")
	 * @ApiReturnParams   (name="images", type="string", required=true, description="商品图组")
	 * @ApiReturnParams   (name="goods_price", type="float", required=true, description="商品单价")
	 * @ApiReturnParams   (name="stock_num", type="integer", required=true, description="商品库存")
	 * @ApiReturnParams   (name="total_num", type="integer", required=true, description="购买数量")
	 * @ApiReturnParams   (name="goods_list['total_price']", type="float", required=true, description="合计价格:仅该商品*购物车数量价格,该项目不展示此字段,支付总价格用goods_list[]同层级的total_price字段")
	 * @ApiReturnParams   (name="total_price", type="float", required=true, description="总支付金额")
	 *
	 * @ApiReturnParams   (name="address_info", type="object", required=true, description="默认地址信息")
	 * @ApiReturnParams   (name="address_info.id", type="integer", required=true, description="默认地址信息id")
	 * @ApiReturnParams   (name="address_info.name", type="string", required=true, description="地址收件人")
	 * @ApiReturnParams   (name="address_info.mobile", type="string", required=true, description="手机号码****")
	 * @ApiReturnParams   (name="address_info.address", type="string", required=true, description="详细地址")
	 * @ApiReturnParams   (name="address_info.address_now", type="string", required=true, description="所在地区")

	 * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
	 * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
	 * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
	 * @ApiReturn   ({
	"code":"状态码",
	"msg": "提示消息"
	})
	 */
	public function settlement() {
		$ids = $this->request->param( 'cart_ids' );
		if ( empty( $ids ) ) {
			$this->error( '请选择需要结算的商品' );
		}

		$model = new \app\api\model\Cart();
		$list  = $model->getListByIds( $ids, $this->auth->id );
		if ( $list['has_error'] ) {
			$this->error( $list['error_msg'] );
		}
		//处理购物车结算数据商品总价格
		$total_price = 0;
		foreach ($list['goods_list'] as &$value){
			$total_price += $value['total_price'];
		}

		//获取默认地址信息
		$userAddressModel     = new UserAddress();
		$field                = 'id,name,mobile,address,address_now';
		$where                = ['user_id' => $this->auth->id, 'is_default' => 1];
		$default_address_info = $userAddressModel->field( $field )->where( $where )->find();
		//手机号*****
		$default_address_info['mobile'] = substr( $default_address_info['mobile'], 0, 3 ) . '****' . substr( $default_address_info['mobile'], 7 );

		$list['address_info']           = $default_address_info;
		$list['total_price'] = $total_price;
		$this->success( '购物车结算数据', $list );
	}

	/**
	 * 购物车结算支付
	 *
	 * @ApiTitle    (购物车结算支付)
	 * @ApiSummary  (购物车结算支付)
	 * @ApiMethod   (POST)
	 * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
	 *
	 * @ApiParams   (name="cart_ids", type="string", required=true, description="购物车ID，多个英文逗号隔开")
	 * @ApiParams   (name="address_id", type="integer", required=true, description="地址ID")
	 * @ApiParams   (name="buy_price", type="float", required=true, description="合计金额")
	 *
	 * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码")
	 * @ApiReturnParams   (name="msg", type="string", required=true, description="提示语")
	 * @ApiReturnParams   (name="data", type="object", description="扩展数据返回")
	 * @ApiReturn   ({
	"code":"状态码",
	"msg": "提示消息"
	})
	 */
//* @ApiParams   (name="voucher_id", type="integer", required=false, description="购物券ID")
//* @ApiParams   (name="coupon_id", type="integer", required=false, description="优惠券ID")
//* @ApiParams   (name="score", type="integer", required=false, description="积分")
//* @ApiParams   (name="remark", type="string", required=false, description="备注")
	public function pay() {
		$rules    = [
			'cart_ids'   => 'require',
			'address_id' => 'require',
			'buy_price'  => 'require',
		];
		$message  = [
			'cart_ids.require'   => '请选择需要结算的商品',
			'address_id.require' => '请选择收货地址',
			'buy_price.require'  => '合计金额不能为空',
		];
		$validate = new Validate( $rules, $message );

		$param = $this->request->param();
		if ( !$validate->check( $param ) ) {
			$this->error( $validate->getError() );
		}
		$ids   = $param['cart_ids'];
		$model = new \app\api\model\Cart();
		$list  = $model->getListByIds( $ids, $this->auth->id );
		if ( empty( $list['goods_list'] ) ) {
			$this->error( '结算商品出错' );
		}
		$address = Db::name( 'user_address' )->where( ['id' => $param['address_id']] )->find();
		if ( empty( $address ) ) {
			$this->error( '地址不存在' );
		}
		$userId = $this->auth->id;
//		if ( !empty( $param['score'] ) ) {
//			$userScore = Db::name( 'user' )->where( ['id' => $userId] )->value( 'score' );
//			if ( $param['score'] > $userScore ) {
//				$this->error( '积分不足' );
//			}
//		}
//		if ( !empty( $param['coupon_id'] ) ) {
//			$couponIds = array_column( $list['coupon_list'], 'id' );
//			if ( in_array( $param['coupon_id'], $couponIds ) ) {
//				$coupon = Db::name( 'user_coupon' )->where( ['id' => $param['coupon_id']] )->find();
//			}
//		} elseif ( !empty( $param['voucher_id'] ) ) {
//			$voucherIds = array_column( $list['voucher_list'], 'id' );
//			if ( in_array( $param['voucher_id'], $voucherIds ) ) {
//				$voucher = Db::name( 'user_voucher' )->where( ['id' => $param['voucher_id']] )->find();
//			}
//		}
		Db::startTrans();
		$orderModel = new Order();
		$orderNo    = get_order_sn( 'D' );
//		$couponPrice  = empty( $coupon ) ? 0 : $coupon['price'];
//		$voucherPrice = empty( $voucher ) ? 0 : $voucher['price'];
//		$scorePrice   = empty( $param['score'] ) ? 0 : bcmul( $param['score'], $list['score_change_price'], 2 );
//		$payPrice     = $list['amount_price'] - $couponPrice - $voucherPrice - $scorePrice + $list['express_price'];
		$payPrice = $param['buy_price'];
		$status   = 1;
		if ( $payPrice < 0 ) {
			$status   = 2;
			$payPrice = 0;
		}
		$orderData = [
			'order_no'     => $orderNo,
			'pay_order_no' => $orderNo,
			'user_id'      => $userId,
//			'total_price'       => $list['total_price'], //商品金额  购物车结算时创建一个订单 对应 两个 商品订单
//			'amount_price'      => $list['amount_price'],
			'pay_price'    => $payPrice,
//			'express_price'     => $list['express_price'],
//			'active_save_price' => $list['save_price'],
//			'give_score'        => $list['give_score'],
//			'coupon_price'      => $couponPrice,
//			'voucher_price'     => $voucherPrice,
//			'score_price'       => $scorePrice,
//			'score'             => $param['score'],
//			'remark'            => $param['remark'],
			'sh_name'      => $address['name'],
			'sh_mobile'    => $address['mobile'],
			'sh_address'   => $address['address_now'] . '-' . $address['address'],
			'order_status' => $status,
			'createtime'   => time()
		];
		$id        = $orderModel->insertGetId( $orderData );
//		$id = $orderModel->id;
//		if ( !empty( $coupon ) ) {
//			Db::name( 'user_coupon' )->where( ['id' => $coupon['id']] )->update( ['status' => 2, 'order_id' => $id] );
//		}
//		$voucherDiffPrice = 0;
//		if ( !empty( $voucher ) ) {
//			$voucherDiffPrice = $voucher['pay_price'];
//			Db::name( 'user_voucher' )->where( ['id' => $voucher['id']] )->update( ['status' => 2, 'order_id' => $id] );
//		}
		$goodsData = [];
		// 更新商品库存 (下单减库存)
		$deductStockData = [];
//		$diffPrice       = 0;
		foreach ( $list['goods_list'] as $k => $v ) {
//			$total_diff_price = ( $v['goods_price'] - $v['goods_sku']['cost_price'] ) * $v['total_num'];
//			$diffPrice        += $total_diff_price;
			$goodsData[] = [
				'order_id'          => $id,
				'goods_name'        => $v['name'],
				'goods_id'          => $v['id'],
				'goods_no'          => $v['goods_no'],
				'describe'          => $v['describe'],
				'image'             => $v['image'],
				'deduct_stock_type' => $v['deduct_stock_type'],
//				'spec_type'         => $v['spec_type'],
//				'spec_sku_id'       => $v['goods_sku']['spec_sku_id'],
//				'goods_spec_id'     => $v['goods_sku']['goods_spec_id'],
//				'goods_attr'        => $v['goods_sku']['goods_attr'],
				'goods_price'       => $v['goods_price'],
				'total_num'         => $v['total_num'],
				'total_price'       => $v['total_price'],
//				'line_price'        => $v['goods_sku']['goods_price'],
//				'cost_price'        => $v['goods_sku']['cost_price'],
//				'diff_price'        => $v['goods_price'] - $v['goods_sku']['cost_price'],
//				'total_diff_price'  => $total_diff_price,
				'user_id'           => $userId,
//				'save_price'        => $v['save_price'],
//				'is_gift'           => $v['is_gift'],
//				'active_id'         => empty( $v['active'][0] ) ? 0 : $v['active'][0]['id'],
//				'active_remark'     => empty( $v['active'][0] ) ? '' : $v['active'][0]['name'],
			];
			// 下单减库存
//			$v['deduct_stock_type'] === '10' && $deductStockData[] = [
//				'goods_spec_id' => $v['goods_sku']['goods_spec_id'],
//				'stock_num'     => ['dec', $v['total_num']]
//			];
		}
//		$diffPrice = $orderData['pay_price'] - $list['cost_price'] + $voucherDiffPrice;
//		$orderModel->save( ['diff_price' => $diffPrice] );
		$goodsModel = new OrderGoods();
		$goodsModel->saveAll( $goodsData );
		// 更新商品库存
//		!empty( $deductStockData ) && ( new ShopGoodsSpec() )->isUpdate()->saveAll( $deductStockData );

//		if ( $status == 2 ) {
//			Db::commit();
//			$this->success( '下单成功', ['jsApiParameters' => null, 'id' => $id] );
//		}
//		if ( $id ) {
//			$cart_ids = explode( ',', $param['cart_ids'] );
//			foreach ( $cart_ids as $v ) {
//				//获取购物车中的商品id
////				$userCartModel = new \app\api\model\Cart();
//				$cartGoodsInfo = Db::name('cart')->where( 'id', $v )->find();
//				//减库存
//				Db::name( 'shop_goods' )->where( 'id', $cartGoodsInfo['goods_id'] )->setDec( 'stock_num', $cartGoodsInfo['num'] );
//			}
//		}
		//结算时 删除购物车结算商品
		Db::name( 'cart' )->where( ['id' => ['in', $param['cart_ids']]] )->delete();

//		Db::commit(); //测试提交 未支付提交事务 测试添加数据
		//确认订单->唤起微信支付信息->返回支付信息
		$order_info = $orderModel->where( 'id', $id )->find();
		$payservice = new \addons\epay\library\Service();
		//提交预支付订单参数
		$order_param = [
			'amount'    => $order_info['pay_price'],
			'orderid'   => $order_info['order_no'],
			'type'      => 'wechat', //微信
			'title'     => '购物车结算',
			'notifyurl' => $this->request->domain() . '/api/notify/service/type/wechat',
			'returnurl' => '',
			'method'    => 'mp', //公众号
			'openid'    => $param['open_id'],
		];
		$result      = $payservice::submitOrder( $order_param );
		if ($result){
			Db::commit();
			$this->success( '支付信息', ['payDetail' => $result, 'order_id' => $order_info['id']] );
		}else{
			Db::rollback();
			$this->error( '支付参数错误' );
		}

		//todo 虚拟金额
		//$orderData['pay_price']=0.01;
//		$openid     = Db::name( 'third' )->where( ['user_id' => $userId] )->value( 'openid' );
//		$attributes = [
//			'trade_type'   => 'JSAPI',
//			'body'         => '订单支付',
//			'detail'       => '订单支付',
//			'out_trade_no' => $orderNo,
//			'total_fee'    => $orderData['pay_price'] * 100, // 单位：分
//			'notify_url'   => url( 'order/notify', [], true, true ),
//			'openid'       => $openid,
//		];
//
//		$order   = new WxOrder( $attributes );
//		$app     = new Application( ConfigService::load() );
//		$payment = $app->payment;
//		$result  = $payment->prepare( $order );
//		if ( $result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS' ) {
//			$prepayId        = $result->prepay_id;
//			$jsApiParameters = $payment->configForJSSDKPayment( $prepayId );
//			Db::commit();
//			$this->success( '预支付', ['jsApiParameters' => $jsApiParameters, 'id' => $id] );
//		} else {
//			Db::rollback();
//			$this->error( '支付参数错误', $result );
//		}

	}


}

